<?php


namespace App\Service;

use App\Models\ArticleCode;
use App\Models\CodeBatch;
use Illuminate\Support\Facades\Storage;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class QrcodeService
{
    /**
     * 生成8位唯一码
     * @return string
     */
    protected function makeSoleCode(){
        $code = 'abcdefghijklmnopqresuvwxyz';
        $rand = $code[rand(0, 25)]
            . strtoupper(dechex(date('m')))
            . date('d') . substr(time(), -5)
            . substr(microtime(), 2, 5)
            . sprintf('%02d', rand(0, 99));
        for (
            $a = md5($rand, true),
            $s = '0123456789abcdefghijklmnopqrstuv',
            $d = '',
            $f = 0;
            $f < 8;
            $g = ord($a[$f]),
            $d .= $s[($g ^ ord($a[$f + 8])) - $g & 0x1F],
            $f++
        ) ;
        return $d;
    }

    /**
     * 生成二维码
     * @param $str
     * @param $catalog
     * @param $soleCode
     * @return mixed
     */
    protected function makeQrcode($str,$catalog,$soleCode){
        $path = config('filesystems');
        $path = $path['disks']['qrcode']['root'];
        if (!is_dir($path.'/'.$catalog)){
            mkdir($path.'/'.$catalog);
        }
        $fileName = $catalog.'/'.$soleCode . '.png';
        QrCode::format('png')->size(500)->generate($str, $path . '/' . $fileName);
        $url =  Storage::disk('qrcode')->url($fileName);
        return ['url'=>$url,'path'=>$path . '/' . $fileName];
    }

    /**
     * 批量生产二维码
     * @param CodeBatch $batch
     * @return array
     */
    public function batchMakeQrcode(CodeBatch $batch){
        $nums = $batch->nums;
        $url = env('FRONT_URL')."?id={$batch->article_id}";
        $catalog = 'QrCode'.$batch->id;
        for ($i=0;$i<$nums;$i++){
            $soleCode = $this->makeSoleCode();
            $qrcode = $this->makeQrcode($url,$catalog,$soleCode);
            $data['qrcode_url'] = $qrcode['url'];
            $data['qrcode_path'] = $qrcode['path'];
            $data['code'] = $soleCode;
            $data['batch_id'] = $batch->id;
            $data['article_id'] = $batch->article_id;
            $model = new ArticleCode();
            $model->fill($data)->save();
        }
        $path = config('filesystems');
        $path = $path['disks']['qrcode']['root'];
        $zip = new \ZipArchive();
        $zipFileName = $catalog."/$catalog.zip";
        $file_list = ArticleCode::where('batch_id',$batch->id)->get()->pluck('qrcode_path');
        if ($zip->open($path.'/'.$zipFileName, \ZipArchive::CREATE) !== true) {
            exit('无法打开文件，或者文件创建失败');
        }
        foreach ($file_list as $val) {
            if (file_exists($val)) {
                $zip->addFile($val,basename($val));
            }
        }
        $zip->close();
        return [
            'status' =>1,
            'directory'=> $path.'/'.$catalog,
            'download_url' => Storage::disk('qrcode')->url($zipFileName)
        ];
    }

}